﻿Imports System.IO

''' <summary>
''' Controller extension class that adds controller methods
''' to render a partial view and return the result as string.
''' 
''' Based on http://craftycodeblog.com/2010/05/15/asp-net-mvc-render-partial-view-to-string/
''' </summary>
Namespace Utilitys
    Public NotInheritable Class ControllerExtension
        
        ''' <summary>
        ''' Renders a (partial) view to string.
        ''' </summary>
        ''' <param name="controller">Controller to extend</param>
        ''' <param name="viewName">(Partial) view to render</param>
        ''' <returns>Rendered (partial) view as string</returns>
        Public Shared Function RenderPartialViewToString(controller As Controller, viewName As String) As String
            Return ControllerExtension.RenderPartialViewToString(controller, viewName, Nothing)
        End Function

        ''' <summary>
        ''' Renders a (partial) view to string.
        ''' </summary>
        ''' <param name="controller">Controller to extend</param>
        ''' <param name="viewName">(Partial) view to render</param>
        ''' <param name="model">Model</param>
        ''' <returns>Rendered (partial) view as string</returns>
        Public Shared Function RenderPartialViewToString(controller As Controller, viewName As String, model As Object) As String
            If String.IsNullOrEmpty(viewName) Then
                viewName = controller.ControllerContext.RouteData.GetRequiredString("action")
            End If

            controller.ViewData.Model = model

            Using sw = New StringWriter()
                Dim viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName)
                Dim viewContext = New ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw)
                viewResult.View.Render(viewContext, sw)

                Return sw.GetStringBuilder().ToString()
            End Using
        End Function

    End Class
End Namespace